CKEDITOR.plugins.add('smartfreetable', {
	icons: 'smartfreetable',
	requires: 'widget',
	init: function(editor) {
		CKEDITOR.addCss('th, td { white-space: nowrap; }');
		var cls = 'smartfreetable-preview';

		editor.on('doubleclick', function(evt) {
			var element = evt.data.element;
			var findOne = false;
			// 找到点击元素的顶点元素
			while (true) {
				if (element.is('div') && element.hasClass(cls)) {
					findOne = true;
					break;
				} else if (element.is('body')) {
					break;
				}
				element = element.getParent();
			}

			if (findOne) {
				var id = element.getAttribute('id');
				var info = $_doc.data(id);
				if (info) {
					var mergedCellInfos = info.mergedCellInfos;
					var data = info.data;
					var cellMetas = info.cellMetas;

					jQuery.fn.showFreeTable({
						"id": id,
						"element": element,
						"mergedCellInfos": mergedCellInfos,
						"data": data,
						"cellMetas": cellMetas
					});
				} else {
					ck.util.showMsg(2, '数据正在加载');
				}
			}
		});
		editor.widgets.add('smartfreetable', {
			button: '自定义表格',
			draggable: false,
			requiredContent: 'div(simplebox)',
			template: '<div class="simplebox ' + cls + '"><div class="simplebox-content"></div></div>',
			init: function() {
				var element = this.element;
				var id = element.getAttribute('id');
				if (id) {
					function doSome(dbData) {
						var hotData = dbData.page.hotData;
						var hotObj = JSON.parse(hotData);
						var data = hotObj.data;
						var readTabHtml = dbData.page.readTabHtml;
						var freeTabHtml = dbData.page.freeTabHtml;
						var mergedCellInfos = hotObj.mergedCellInfos;
						$_doc.data(id, hotObj);

						var insertEle = element.findOne('.simplebox-content');
						if (CKEDITOR.isFreeTabClone == true) {
							CKEDITOR.isFreeTabClone = false;
							var childNodeList = insertEle.getChildren();
							for (var i = insertEle.getChildCount() - 1; i >= 0; i--) {
								childNodeList.getItem(i).remove();
							}
						} else {
							// 删除 br 标签
							insertEle.getChildren().getItem(0).remove();
						}

						jQuery.fn.insertCkFreeTableHtml(readTabHtml, freeTabHtml, insertEle, dbData.simpleUseArgs);
					}
					ck.util.sendAjax({
						url: 'freeTable/getFreeTab',
						data: {
							pageId: pageId,
							freeTabId: id
						}
					}, doSome);
				} else {
					id = ck.util.randomString(16, 'aA');
					element.setAttribute('id', id);
					var freeForInit = true;
					jQuery.fn.showFreeTable({
						id,
						element,
						freeForInit
					});
				}

				// 为widget添加导出图标
				$(element.$).hover(jQuery.fn.widgetMouseOver, jQuery.fn.widgetMouseOut).onPositionChanged(jQuery.fn.showIcon);

			},
			upcast: function(el, data) {
				if (el.name == 'div' && el.hasClass(cls)) {
					var len = el.children[0].children.length;
					if (len == 3) {
						el.children[0].children[2].remove();
						el.children[0].children[1].remove();
					}
					return el;
				}
			}
		});
	}
});